package com.kstech.ks_gaz01.base

import android.util.Log
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.navArgs
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.blankii.androidlibrary.base.BaseBindingFragment
import com.blankii.androidlibrary.exts.logd
import com.kstech.ks_gaz01.XML_ADDRESS_MIN_MAX
import com.kstech.ks_gaz01.XML_ADDRESS_SAVE_PARAM
import com.kstech.ks_gaz01.XML_ADDRESS_SAVE_PARAM_SUCESS
import com.kstech.ks_gaz01.XML_ADDRESS_SENSOR_SUCCESS
import com.kstech.ks_gaz01.XML_ADDRESS_SETTING_BUTTON
import com.kstech.ks_gaz01.XML_ADDRESS_SIMULATION_CHOOSE
import com.kstech.ks_gaz01.XML_ADDRESS_SIMULATION_DATAHEAD
import com.kstech.ks_gaz01.XML_ADDRESS_SIMULATION_HEART
import com.kstech.ks_gaz01.XML_ADDRESS_SIMULATION_OPEN
import com.kstech.ks_gaz01.XML_ADDRESS_WRITE_START_WORK
import com.kstech.ks_gaz01.XML_GROUP_ADDRESS_FAULT
import com.kstech.ks_gaz01.XML_IS_SINGLE_CONTROL
import com.kstech.ks_gaz01.currentCarName
import com.kstech.ks_gaz01.data.DebugDataBean
import com.kstech.ks_gaz01.databinding.FragmentHomeBinding
import com.kstech.ks_gaz01.fragments.ConfigFragment
import com.kstech.ks_gaz01.fragments.RealTimePartFragment
import com.kstech.ks_gaz01.manager.ParseXmlManager
import com.kstech.ks_gaz01.socket.SocketManagerNew

/**
 * author: blankii
 * created on: 2024/4/25 13:41
 * description:
 * 1 viewPager2 是基于RecyclerView的，所以它使用的Adapter也是RecyclerView的Adapter
 * 2 homeFragment（fragmentA fragmentB） 跳转到newFragment生命周期：
 * homeFragment-onPause、onStop newFragment-onCreate、onStart。onResume   (fragmentA fragmentB生命周期不发生变化)
 * 3 fragmentA 滑动到fragmentB时 生命周期：
 * fragmentA-onPause  fragmentB-onCreate、onStart、onResume 或者fragmentB-onResume(一定是先onPause 再onResume)
 */
class HomeFragment : BaseBindingFragment<FragmentHomeBinding>(FragmentHomeBinding::inflate) {
    private val args: HomeFragmentArgs by navArgs()
    private val fragments = listOf<Fragment>(ConfigFragment(), RealTimePartFragment())
    private lateinit var mViewModel: HomeViewModel
    private val VIEWPAGE_CONFIG = 0
    private val VIEWPAGE_REALTIME = 1
    private var mViewPagerPage = VIEWPAGE_CONFIG


    //viewPager 适配器
    class MainViewpager2Adapter(
        fragmentActivity: FragmentActivity, private val fragments: List<Fragment>
    ) : FragmentStateAdapter(fragmentActivity) {
        override fun getItemCount(): Int = fragments.size

        override fun createFragment(position: Int): Fragment = fragments[position]
    }

    override fun onCreateInit() {
        //todo 需要整理修改
        "打开车型文件:${args.fileName.toString()}".logd(TAG)
//        currentCarName = args.fileName.toString()
//        if (currentCarName.contains("GNH16")) {
//            gz_size = 5
//        } else if (currentCarName.contains("GNQ20")) {
//            gz_size = 5
//        } else {
//            gz_size = 2
//        }
        /**
         * 主线程 加载XML 配置文件
         * 阻塞一下主线程
         */
        ParseXmlManager().pullParseXml(requireContext(), currentCarName)
        //是否是单控制器
        val isSingleControl = DebugDataBean.xmlSettings[XML_IS_SINGLE_CONTROL]!!
//        Log.e(TAG, "onCreateInit: 是否单控制器$isSingleControl", )
        if (isSingleControl) {
            XML_ADDRESS_SETTING_BUTTON = "41000"
            XML_ADDRESS_MIN_MAX = "43701"//单控制器没有，暂时还是双控制器的地址
            XML_ADDRESS_SENSOR_SUCCESS = "41002"
            XML_ADDRESS_SAVE_PARAM = "41003"
            XML_ADDRESS_SAVE_PARAM_SUCESS = "41006"
            XML_ADDRESS_WRITE_START_WORK = "41009"//双控制器43706 单控制器41009
            XML_GROUP_ADDRESS_FAULT = "41100"
            /**
             * 仿真 一般车型没有基本不用改
             */
            XML_ADDRESS_SIMULATION_HEART = "41050"
            XML_ADDRESS_SIMULATION_OPEN = "41010"
            XML_ADDRESS_SIMULATION_DATAHEAD = "44362"
            XML_ADDRESS_SIMULATION_CHOOSE = "44361"
            //单控制器新地址(侯林添加)
        } else {
            XML_ADDRESS_SETTING_BUTTON = "43700"
            XML_ADDRESS_MIN_MAX = "43701"
            XML_ADDRESS_SENSOR_SUCCESS = "43702"
            XML_ADDRESS_SAVE_PARAM = "43705"
            XML_ADDRESS_SAVE_PARAM_SUCESS = "43706"
            XML_ADDRESS_WRITE_START_WORK = "43709"//双控制器43706 单控制器41009
            XML_GROUP_ADDRESS_FAULT = "44460"
            /**
             * 仿真 一般车型没有基本不用改
             */
            XML_ADDRESS_SIMULATION_HEART = "44360"
            XML_ADDRESS_SIMULATION_OPEN = "43710"
            XML_ADDRESS_SIMULATION_DATAHEAD = "44362"
            XML_ADDRESS_SIMULATION_CHOOSE = "44361"
        }
    }

    override fun onInitView() {
        showViewPager()
        mViewModel = ViewModelProvider(requireActivity())[HomeViewModel::class.java]
        mViewModel.currentPage.observe(this, Observer {
            if (it == FragmentPage.HOME_FRAG && mViewPagerPage == VIEWPAGE_CONFIG) {
                mViewModel.currentPage.value = FragmentPage.HOME_CONFIG
            } else if (it == FragmentPage.HOME_FRAG && mViewPagerPage == VIEWPAGE_REALTIME) {
                mViewModel.currentPage.value = FragmentPage.HOME_REALTIME
            }
//            else {
//                "else:${it}".loge(TAG)
//            }
        })
    }

    /**
     * todo viewPager2 可以考虑增加切换动画
     */
    private fun showViewPager() {
        binding.apply {
            //增加页面之间的间隔
//            viewpager2.setPageTransformer(MarginPageTransformer(30))
            val adapter = MainViewpager2Adapter(
                this@HomeFragment.requireActivity(), fragments
            )
            viewpager2.adapter = adapter
            //todo viewPager2 缓存左右两边的页面  #暂时不可以直接使用，会因为生命周期的原因导致错乱，需要优化重构fragment结构
//            viewpager2.offscreenPageLimit = 1
            viewpager2.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
                override fun onPageSelected(position: Int) {
                    super.onPageSelected(position)
                    when (position) {
                        0 -> {
                            mViewPagerPage = VIEWPAGE_CONFIG
                        }

                        1 -> {
                            mViewPagerPage = VIEWPAGE_REALTIME
                        }
                    }
                }
            })
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        SocketManagerNew.closeThread()
        Log.e(TAG, "onDestroy: blankii")
    }

}